package stone;

public class OptStoneObject {

	public static class AccessException extends Exception {}
	
	protected OptClassInfo classInfo;
	protected Object[] fields;
	
	public OptStoneObject(OptClassInfo ci, int size) {
		classInfo = ci;
		fields = new Object[size];
	}
	
	public OptClassInfo classInfo() {
		return classInfo;
	}
	
	public Object read(String name) throws AccessException {
		Integer i = classInfo.fieldIndex(name);
		if (i != null) {
			return fields[i];
		}
		else {
			i = classInfo.methodIndex(name);
			if (i != null) {
				return method(i);
			}
		}
		throw new AccessException();
	}
	
	public void write(String name, Object value) throws AccessException {
		// 根据字段名将字段值写入(不能对方法做出改变)
		// 首先查找字段在fields中的下标
		// 若未找到，则抛出异常
		// 否则，将字段值写入index所在的fields值域内
		Integer i = classInfo.fieldIndex(name);
		if (i == null) {
			throw new AccessException();
		}
		else {
			fields[i] = value;
		}
	}
	
	public Object read(int index) {
		// 根据下标读取字段值
		return fields[index];
	}
	
	public void write(int index, Object value) {
		// 将value写入到fields下标为index的位置
		fields[index] = value;
	}
	
	public Object method(int index) {
		return classInfo.method(this, index);
	}
	
	
}
